package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("sessions")
public class SessionsController {

    @Autowired
    private IUserService userService;
    //登录虽然是查询数据库应该使用get请求方式,但是增加了一个session缓存,所以应该用post新增请求方式
    @PostMapping
    //@RequestParam表示必须携带这个参数才能进入该方法
    public JSONResult login(@RequestParam String email, @RequestParam String password){
        JSONResult result = new JSONResult();
        try {
            //登录成功之后显示当前用户信息
            User user = userService.login(email, password);
            //将用户信息存入session
            UserContext.setCurrentUser(user);

            //将用户信息塞入result,返回给页面
            result.setData(user);

        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }
    //清除session数据
    @DeleteMapping
    public JSONResult logout(HttpSession session){
        session.removeAttribute("USER_IN_SESSION");
        return new JSONResult();
    }

}
